package com.dhcc.sdc.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReferenceUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.sdc.cdss.dao.*;
import com.dhcc.sdc.cdss.dto.CdssLabAndExamDto;
import com.dhcc.sdc.cdss.entity.*;
import com.dhcc.sdc.cdss.service.*;
import com.dhcc.sdc.base.entity.CdssRecommendKeywordEntity;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sdc.base.service.ICdssRecommendKeywordService;
import com.dhcc.sdc.base.service.ICdssStandardMatchService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.standard.entity.SdsStandSourceFieldEntity;
import com.dhcc.sds.standard.service.ISdsStandSourceFieldService;
import com.dhcc.sds.standard.service.ISdsStandSourceService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @author zhangdc
 * @version 1.0
 * @date 2022/7/1 10:18
 */
@Service
public class CdssStandardMatchServiceImpl implements ICdssStandardMatchService {

    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private ISdcCdssNursingService cdssNursingService;
    @Autowired
    private ISdcCdssEvalService cdssEvalService;
    @Autowired
    private ISdcCdssExamService cdssExamService;
    @Autowired
    private ISdcCdssLabService cdssLabService;
    @Autowired
    private ISdcCdssTreatService cdssTreatService;
    @Autowired
    private ICdssRecommendKeywordService cdssRecommendKeywordService;
    @Autowired
    private ISdsStandSourceService standSourceService;
    @Autowired
    private ISdsStandSourceFieldService sdsStandSourceFieldService;
    @Resource
    private SdcCdssItemMapper sdcCdssItemMapper;
    @Resource
    private SdcCdssItemMatchMapper sdcCdssItemMatchMapper;
    @Autowired
    private ISdcCdssItemService sdcCdssItemService;
    double all = 1;
    Double cur = (double) 0;


    @Override
    public List<ZTreeNode> buildCdssRecommendTree() {
        List<ZTreeNode> res = new ArrayList<>();
        List<ZTreeNode> parentList =  sdcCdssItemMapper.getEntityTree();
        List<ZTreeNode> children1List =  new ArrayList<>();
        List<ZTreeNode> children2EvalList=  sdcCdssItemMapper.getCdssTree(1);
        List<ZTreeNode> children2TreatList=  sdcCdssItemMapper.getCdssTree(4);
        List<ZTreeNode> children2ExamList=  sdcCdssItemMapper.getCdssTree(2);
        List<ZTreeNode> children2LabList=  sdcCdssItemMapper.getCdssTree(3);
        List<ZTreeNode> children2NurList=  sdcCdssItemMapper.getCdssTree(5);


        List<DictionaryEntity> dictionaryEntities = dictionaryService.queryByTypeCode("SDS", "CDSSRecommendType");
        for (ZTreeNode zTreeNode : parentList){
            for (DictionaryEntity dictionaryEntity : dictionaryEntities){
                ZTreeNode children1 = new ZTreeNode();
                long id = IdWorker.getId();
                children1.setId(id);
                children1.setpId(zTreeNode.getId());
                children1.setName(dictionaryEntity.getDescription());
                children1List.add(children1);
            }
        }

       for (ZTreeNode zTreeNode1 : children1List){
           String name = zTreeNode1.getName();
           switch (name) {
               case "推荐护理处置":
                   for (ZTreeNode zTreeNode2Nur : children2NurList){
                       if (zTreeNode2Nur.getpId().equals(zTreeNode1.getpId())){
                           zTreeNode2Nur.setPinyin(name);
                           zTreeNode2Nur.setpId(zTreeNode1.getId());
                       }
                   }
                   break;
               case "推荐检验":
                   for (ZTreeNode zTreeNode2Lab : children2LabList){
                       if (zTreeNode2Lab.getpId().equals(zTreeNode1.getpId())){
                           zTreeNode2Lab.setPinyin(name);
                           zTreeNode2Lab.setpId(zTreeNode1.getId());
                       }
                   }
                   break;
               case "推荐检查":
                   for (ZTreeNode zTreeNode2Exam : children2ExamList){
                       if (zTreeNode2Exam.getpId().equals(zTreeNode1.getpId())){
                           zTreeNode2Exam.setPinyin(name);
                           zTreeNode2Exam.setpId(zTreeNode1.getId());
                       }
                   }
                   break;
               case "推荐治疗方案":
                   for (ZTreeNode zTreeNode2Treat : children2TreatList){
                       if (zTreeNode2Treat.getpId().equals(zTreeNode1.getpId())){
                           zTreeNode2Treat.setPinyin(name);
                           zTreeNode2Treat.setpId(zTreeNode1.getId());
                       }
                   }
                   break;
               case "推荐评估量表":
                   for (ZTreeNode zTreeNode2Eval : children2EvalList){
                       if (zTreeNode2Eval.getpId().equals(zTreeNode1.getpId())){
                           zTreeNode2Eval.setPinyin(name);
                           zTreeNode2Eval.setpId(zTreeNode1.getId());
                       }
                   }
                   break;
           }
       }

        res.addAll(parentList);
        res.addAll(children1List);
        res.addAll(children2EvalList);
        res.addAll(children2TreatList);
        res.addAll(children2ExamList);
        res.addAll(children2LabList);
        res.addAll(children2NurList);

        return res;
    }

    @Override
    public void autoCompare(Long cdssRecommendId, String cdssRecommendName, String recommendType) {

            List<CdssRecommendKeywordEntity> cdssRecommendKeywordEntities = new ArrayList<>();
            if ("".equals(cdssRecommendName)) {
                //匹配全部
                cdssRecommendKeywordEntities = cdssRecommendKeywordService.selectList(null);
            } else {
                //匹配当前节点
                // 只根据itemID匹配有问题，增加病种的限定
                SdcCdssItemEntity sdcCdssItemEntity = sdcCdssItemMapper.selectById(cdssRecommendId);
//            String itemId = cdssRecommendKeywordService.getItemIdByType(cdssRecommendId, recommendType);
                cdssRecommendKeywordEntities = cdssRecommendKeywordService.selectList(new EntityWrapper<CdssRecommendKeywordEntity>()
                        .eq("item_id", sdcCdssItemEntity.getItemId()).eq("qcentity_id", sdcCdssItemEntity.getQcentityId()));
            }
            for (CdssRecommendKeywordEntity cdssRecommendKeywordEntity : cdssRecommendKeywordEntities) {
                //String recommendType = cdssRecommendKeywordEntity.getRecommendType();
                recommendType = cdssRecommendKeywordEntity.getRecommendType();
                String keyword = cdssRecommendKeywordEntity.getKeyword();
                String[] split = keyword.split(",");
                List<String> list;
                if ("推荐评估量表".equals(recommendType)) {
                    list = this.handleEvalRegexp(split);
                } else {
                    list = this.handleRegexp(split);
                }

                //排除sql
                String filterTxt = list.get(0);
                //同时满足sql
                String keywordAndTxt = list.get(1);
                //满足一个sql
                String keywordOrTxt = list.get(2);
                List<Long> matchIds = new ArrayList<>();
                switch (recommendType) {
                    case "推荐检查":
                        //过滤医嘱为检查的
                        CdcDictionaryEntity dictionaryEntity = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "Check");
                        //查询满足的检查医嘱id
                        matchIds = sdcCdssItemMatchMapper.compareOrderByRegexp(filterTxt, keywordAndTxt, keywordOrTxt, dictionaryEntity.getId());
                        break;
                    case "推荐检验":
                        //过滤医嘱为检验的
                        CdcDictionaryEntity dictionaryEntity2 = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "Lab");
                        //查询满足的检查医嘱id
                        matchIds = sdcCdssItemMatchMapper.compareOrderByRegexp(filterTxt, keywordAndTxt, keywordOrTxt, dictionaryEntity2.getId());
                        break;
                    case "推荐评估量表":
                        matchIds = sdcCdssItemMatchMapper.compareEvalByRegexp(filterTxt, keywordAndTxt, keywordOrTxt);
                        break;
                    case "推荐治疗方案":
                        matchIds = sdcCdssItemMatchMapper.compareOrderByRegexp(filterTxt, keywordAndTxt, keywordOrTxt, null);
                        break;
                    case "推荐护理处置":
                        matchIds = sdcCdssItemMatchMapper.compareOrderByRegexp(filterTxt, keywordAndTxt, keywordOrTxt, null);
                        break;
                }

                List<SdcCdssItemMatchEntity> sdcCdssItemMatchEntities = new ArrayList<>();
                for (Long matchId : matchIds) {
                    SdcCdssItemMatchEntity sdcCdssItemMatchEntity = new SdcCdssItemMatchEntity();
                    sdcCdssItemMatchEntity.setItemId(cdssRecommendKeywordEntity.getItemId());
                    sdcCdssItemMatchEntity.setMatchId(matchId);
                    sdcCdssItemMatchEntity.setEntityId(cdssRecommendKeywordEntity.getQcentityId());
                    SdcCdssItemMatchEntity cdssItemMatchEntity = sdcCdssItemMatchMapper.selectOne(sdcCdssItemMatchEntity);
                    if (StringUtils.isEmpty(cdssItemMatchEntity)) {
                        sdcCdssItemMatchEntities.add(sdcCdssItemMatchEntity);
                    }
                }
                if (null != sdcCdssItemMatchEntities && sdcCdssItemMatchEntities.size() > 0) {
                    try {
                        sdcCdssItemMatchMapper.insertBatch(sdcCdssItemMatchEntities);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }


    }

    @Override
    public void compare(Long cdssRecommendId, String orderIDStr, String matchType) {
        String[] split = orderIDStr.split(",");
        SdcCdssItemEntity sdcCdssItemEntity = sdcCdssItemMapper.selectById(cdssRecommendId);
        for (String s : split) {
            SdcCdssItemMatchEntity sdcCdssItemMatchEntity = new SdcCdssItemMatchEntity();
            sdcCdssItemMatchEntity.setMatchId(Long.parseLong(s));
            sdcCdssItemMatchEntity.setItemId(sdcCdssItemEntity.getItemId());
            SdcCdssItemMatchEntity cdssItemMatchEntity = sdcCdssItemMatchMapper.selectOne(sdcCdssItemMatchEntity);
            if (StringUtils.isEmpty(cdssItemMatchEntity)) {
                sdcCdssItemMatchMapper.insert(sdcCdssItemMatchEntity);
            }
        }
    }

    @Override
    public void undo(Long cdssRecommendId, String orderIDStr, String matchType) {
        String[] split = orderIDStr.split(",");
        SdcCdssItemEntity sdcCdssItemEntity = sdcCdssItemMapper.selectById(cdssRecommendId);
        for (String s : split){
            SdcCdssItemMatchEntity sdcCdssItemMatchEntity = new SdcCdssItemMatchEntity();
            sdcCdssItemMatchEntity.setMatchId(Long.parseLong(s));
            sdcCdssItemMatchEntity.setItemId(sdcCdssItemEntity.getItemId());
            sdcCdssItemMatchEntity.setEntityId(sdcCdssItemEntity.getQcentityId());
            SdcCdssItemMatchEntity cdssItemMatchEntity = sdcCdssItemMatchMapper.selectOne(sdcCdssItemMatchEntity);
            sdcCdssItemMatchMapper.deleteById(cdssItemMatchEntity.getId());
        }

    }

    @Override
    public void updateIsDefault(Long cdssRecommendId, Long orderID, String matchType, Integer isDefault) {
        SdcCdssItemEntity sdcCdssItemEntity = sdcCdssItemMapper.selectById(cdssRecommendId);
        SdcCdssItemMatchEntity sdcCdssItemMatchEntity = new SdcCdssItemMatchEntity();
        sdcCdssItemMatchEntity.setItemId(sdcCdssItemEntity.getItemId());
        sdcCdssItemMatchEntity.setMatchId(orderID);
        SdcCdssItemMatchEntity cdssItemMatchEntity = sdcCdssItemMatchMapper.selectOne(sdcCdssItemMatchEntity);
        if (!StringUtils.isEmpty(cdssItemMatchEntity)) {
            cdssItemMatchEntity.setIsDefault(isDefault);
            sdcCdssItemMatchMapper.updateById(cdssItemMatchEntity);
        }
    }

    @Override
    public JSONArray findCdssList(Long entityId) {
        JSONArray officeArry = new JSONArray();
        Map<String, Object> map = new HashMap<>();
        map.put("qcentityId", entityId);

        List<SdcCdssItemEntity> list = sdcCdssItemService.list(map);
        for (SdcCdssItemEntity sdcCdssItemEntity : list){
            JSONObject jsObj = new JSONObject();
            jsObj.put("value", sdcCdssItemEntity.getNodeId());
            if (StringUtils.isEmpty(sdcCdssItemEntity.getDataSourceItem())) {
                jsObj.put("text", sdcCdssItemEntity.getItemName());
            } else {
                String name = handleItemName(SdcCdssItemEntity.class, sdcCdssItemEntity);
                jsObj.put("text", name);
            }
            officeArry.add(jsObj);
        }

        return officeArry;
    }

    @Override
    public <T> String handleReferenceTime(Class<T> clazz, T t) {
        String name = "";
        T u = clazz.cast(t);
        String param = null;
        Long dataSource = null, dataSourceItem = null;
        Integer pushStart = null, pushEnd = null, timeUnit = null;
        for (Field field : u.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                if (field.getName().equals("dataSource")) {
                    dataSource = field.get(u) == null ? null : Long.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("param")) {
                    param = field.get(u) == null ? null : String.valueOf(field.get(u));
                } else if (field.getName().equals("dataSourceItem")) {
                    dataSourceItem = field.get(u) == null ? null : Long.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("pushStart")) {
                    pushStart = field.get(u) == null ? null : Integer.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("pushEnd")) {
                    pushEnd = field.get(u) == null ? null : Integer.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("timeUnit")) {
                    timeUnit = field.get(u) == null ? null : Integer.valueOf(String.valueOf(field.get(u)));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if (dataSource != null) {
            SdsStandSourceEntity sourceEntity = standSourceService.selectById(dataSource);
            name = sourceEntity.getSourceDesc();
        }
        if (dataSourceItem != null) {
            SdsStandSourceFieldEntity sourceFieldEntity = sdsStandSourceFieldService.selectById(dataSourceItem);
            name = name + "-" + sourceFieldEntity.getFieldDesc();
        }
        if (param != null) {
            name = name + " (" + param + ")";
        }

        String timeUnitStr = "";
        //1year、2month、3day、 4hour、5minute、6second
        if (timeUnit == 1) {
            timeUnitStr = "year";
        } else if (timeUnit == 2) {
            timeUnitStr = "month";
        } else if (timeUnit == 3) {
            timeUnitStr = "day";
        } else if (timeUnit == 4) {
            timeUnitStr = "hour";
        } else if (timeUnit == 5) {
            timeUnitStr = "minute";
        } else if (timeUnit == 6) {
            timeUnitStr = "second";
        }

        if (pushStart != null) {
            name = name + " " + pushStart;
        } else {
            name = name + " ";
        }
        if (pushEnd != null) {
            name = name + "~" + pushEnd + timeUnitStr;
        } else {
            name = name + "~" + " " + timeUnitStr;
        }


        return name;
    }


    private List<ZTreeNode> handleRecommendInfo(Long children1Id, String description, Long qcentityEntityId) {
        List<ZTreeNode> res = new ArrayList<>();
        switch (description) {
            case "推荐护理处置":
                List<SdcCdssNursingEntity> cdssNursingEntities = cdssNursingService.selectList(new EntityWrapper<SdcCdssNursingEntity>()
                        .eq("qcentity_id", qcentityEntityId)
                        .groupBy("item_id"));
                if (cdssNursingEntities != null && cdssNursingEntities.size() > 0) {
                    for (SdcCdssNursingEntity cdssNursingEntity : cdssNursingEntities) {
                        ZTreeNode children2 = new ZTreeNode();
                        children2.setId(cdssNursingEntity.getId());
                        children2.setpId(children1Id);
                        children2.setName(cdssNursingEntity.getItemName());
                        children2.setPinyin("推荐护理处置");
                        res.add(children2);
                    }
                }
                break;
            case "推荐检验":
                List<SdcCdssLabEntity> cdssLabEntities = cdssLabService.selectList(new EntityWrapper<SdcCdssLabEntity>()
                        .eq("qcentity_id", qcentityEntityId)
                        .groupBy("item_id"));
                if (cdssLabEntities != null && cdssLabEntities.size() > 0) {
                    for (SdcCdssLabEntity cdssLabEntity : cdssLabEntities) {
                        ZTreeNode children2 = new ZTreeNode();
                        children2.setId(cdssLabEntity.getId());
                        children2.setpId(children1Id);
                        children2.setName(cdssLabEntity.getItemName());
                        children2.setPinyin("推荐检验");
                        res.add(children2);
                    }
                }
                break;
            case "推荐检查":
                List<SdcCdssExamEntity> cdssExamEntities = cdssExamService.selectList(new EntityWrapper<SdcCdssExamEntity>()
                        .eq("qcentity_id", qcentityEntityId)
                        .groupBy("item_id"));
                if (cdssExamEntities != null && cdssExamEntities.size() > 0) {
                    for (SdcCdssExamEntity cdssExamEntity : cdssExamEntities) {
                        ZTreeNode children2 = new ZTreeNode();
                        children2.setId(cdssExamEntity.getId());
                        children2.setpId(children1Id);
                        children2.setName(cdssExamEntity.getItemName());
                        children2.setPinyin("推荐检查");
                        res.add(children2);
                    }
                }
                break;
            case "推荐治疗方案":
                List<SdcCdssTreatEntity> cdssTreatEntities = cdssTreatService.selectList(new EntityWrapper<SdcCdssTreatEntity>()
                        .eq("qcentity_id", qcentityEntityId)
                        .groupBy("item_id"));
                if (cdssTreatEntities != null && cdssTreatEntities.size() > 0) {
                    for (SdcCdssTreatEntity cdssTreatEntity : cdssTreatEntities) {
                        ZTreeNode children2 = new ZTreeNode();
                        children2.setId(cdssTreatEntity.getId());
                        children2.setpId(children1Id);
                        children2.setName(cdssTreatEntity.getItemName());
                        children2.setPinyin("推荐治疗方案");
                        res.add(children2);
                    }
                }
                break;
            case "推荐评估量表":
                List<SdcCdssEvalEntity> cdssEvalEntities = cdssEvalService.selectList(new EntityWrapper<SdcCdssEvalEntity>()
                        .eq("qcentity_id", qcentityEntityId)
                        .groupBy("item_id"));
                if (cdssEvalEntities != null && cdssEvalEntities.size() > 0) {
                    for (SdcCdssEvalEntity cdssEvalEntity : cdssEvalEntities) {
                        ZTreeNode children2 = new ZTreeNode();
                        children2.setId(cdssEvalEntity.getId());
                        children2.setpId(children1Id);
                        children2.setName(cdssEvalEntity.getItemName());
                        children2.setPinyin("推荐评估量表");
                        res.add(children2);
                    }
                }
                break;
        }
        return res;
    }

    private List<String> handleRegexp(String[] split) {
        List<String> res = new ArrayList<>();
        //排除sql
        String filterTxt = "";
        //同时满足sql
        String keywordAndTxt = "";
        //满足一个sql
        String keywordOrTxt = "";
        for (String s1 : split) {
            if (s1.contains("!")) {
                filterTxt = filterTxt + "|" + s1.substring(1, s1.length());
            } else if (s1.contains("&")) {
                //同时满足
                String[] split1 = s1.split("&");
                for (int i = 0; i <= split1.length - 1; i++) {
                    if (i == 0) {
                        keywordAndTxt = keywordAndTxt + " or description like '%" + split1[0] + "%'";
                    } else {
                        keywordAndTxt = keywordAndTxt + " and description like '%" + split1[i] + "%'";
                    }
                }
                //keywordAndTxt = keywordAndTxt + " or description like '%" + split1[0] + "%' and description like '%" + split1[1] + "%'";
            } else {
                keywordOrTxt = keywordOrTxt + "|" + s1;
            }
        }
        if ("" != filterTxt) {
            filterTxt = filterTxt.substring(1, filterTxt.length());
        }
        if ("" != keywordOrTxt) {
            keywordOrTxt = keywordOrTxt.substring(1, keywordOrTxt.length());
        }
        if ("" != keywordAndTxt && "" == keywordOrTxt) {
            keywordAndTxt = keywordAndTxt.replaceFirst("or", "and");
        }
        res.add(filterTxt);
        res.add(keywordAndTxt);
        res.add(keywordOrTxt);
        return res;
    }

    private List<String> handleEvalRegexp(String[] split) {
        List<String> res = new ArrayList<>();
        //排除sql
        String filterTxt = "";
        //同时满足sql
        String keywordAndTxt = "";
        //满足一个sql
        String keywordOrTxt = "";
        for (String s1 : split) {
            if (s1.contains("!")) {
                filterTxt = filterTxt + "," + s1.substring(1, s1.length());
            } else if (s1.contains("&")) {
                //同时满足
                String[] split1 = s1.split("&");
                for (int i = 0; i <= split1.length - 1; i++) {
                    if (i == 0) {
                        keywordAndTxt = keywordAndTxt + " or code = '" + split1[0] + "'";
                    } else {
                        keywordAndTxt = keywordAndTxt + " and code = '" + split1[i] + "'";
                    }
                }
                //keywordAndTxt = keywordAndTxt + " or description like '%" + split1[0] + "%' and description like '%" + split1[1] + "%'";
            } else {
                keywordOrTxt = keywordOrTxt + "," + s1;
            }
        }
        if ("" != filterTxt) {
            filterTxt = filterTxt.substring(1, filterTxt.length());
        }
        if ("" != keywordOrTxt) {
            keywordOrTxt = keywordOrTxt.substring(1, keywordOrTxt.length());
        }
        if ("" != keywordAndTxt && "" == keywordOrTxt) {
            keywordAndTxt = keywordAndTxt.replaceFirst("or", "and");
        }
        res.add(filterTxt);
        res.add(keywordAndTxt);
        res.add(keywordOrTxt);
        return res;
    }

    public class BuildCdssData2 extends Thread{
        private Long id;
        private String description;
        private List<ZTreeNode> res;
        private List<CdssLabAndExamDto> cdssDtos;
        private CountDownLatch countDownLatch;

        public BuildCdssData2(Long id, String description, List<ZTreeNode> res, List<CdssLabAndExamDto> cdssDtos, CountDownLatch countDownLatch) {
            this.id = id;
            this.description = description;
            this.res = res;
            this.cdssDtos = cdssDtos;
            this.countDownLatch = countDownLatch;
        }

        public void run() {
            try {
                buildCdssDataMain2(id, description, res, cdssDtos);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();//计数器减1
            }
        }

    }


    public class BuildCdssData extends Thread {

        private SdsQcentityEntity qcEntity;
        private List<ZTreeNode> res;
        private List<DictionaryEntity> dictionaryEntities;
        private CountDownLatch countDownLatch;

        public BuildCdssData(SdsQcentityEntity qcEntity, List<ZTreeNode> res, List<DictionaryEntity> dictionaryEntities, CountDownLatch countDownLatch) {
            this.qcEntity = qcEntity;
            this.res = res;
            this.dictionaryEntities = dictionaryEntities;
            this.countDownLatch = countDownLatch;
        }

        public void run() {
            try {
                buildCdssDataMain(qcEntity, res, dictionaryEntities);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();//计数器减1
            }
        }

    }

    private void buildCdssDataMain(SdsQcentityEntity qcEntity, List<ZTreeNode> res, List<DictionaryEntity> dictionaryEntities) {
        handleCdssData(qcEntity, res, dictionaryEntities);
        synchronized (cur) {
            cur++;
        }
    }

    private void buildCdssDataMain2(Long id, String description, List<ZTreeNode> res, List<CdssLabAndExamDto> cdssDtos) {
        for (CdssLabAndExamDto cdssDto : cdssDtos){
            ZTreeNode children2 = new ZTreeNode();
            children2.setId(cdssDto.getId());
            children2.setpId(id);
            children2.setName(cdssDto.getItemName());
            children2.setPinyin(description);
            res.add(children2);
        }
    }

    private void handleCdssData(SdsQcentityEntity qcEntity, List<ZTreeNode> res, List<DictionaryEntity> dictionaryEntities) {
        ZTreeNode parent = new ZTreeNode();
        parent.setId(qcEntity.getId());
        parent.setpId(0l);
        parent.setName(qcEntity.getBtDesc());
        parent.setIsOpen(true);
        if (StringUtils.isEmpty(qcEntity.getId())) {
            return;
        }
        for (DictionaryEntity dictionaryEntity : dictionaryEntities) {
            ZTreeNode children1 = new ZTreeNode();
            long id = IdWorker.getId();
            children1.setId(id);
            children1.setpId(qcEntity.getId());
            children1.setName(dictionaryEntity.getDescription());
            res.add(children1);
            List<ZTreeNode> children2 = handleRecommendInfo(id, dictionaryEntity.getDescription(), qcEntity.getId());
            res.addAll(children2);
        }
        res.add(parent);
    }


    private <T> String handleItemName(Class<T> clazz, T cla) {
        String name = "";
        T u = clazz.cast(cla);
        String itemName = null, param = null;
        Long dataSource = null, dataSourceItem = null;
        Integer pushStart = null, pushEnd = null, timeUnit = null;
        for (Field field : u.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                if (field.getName().equals("itemName")) {
                    itemName = field.get(u) == null ? null : String.valueOf(field.get(u));
                } else if (field.getName().equals(" ")) {
                    dataSource = field.get(u) == null ? null : Long.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("param")) {
                    param = field.get(u) == null ? null : String.valueOf(field.get(u));
                } else if (field.getName().equals("dataSourceItem")) {
                    dataSourceItem = field.get(u) == null ? null : Long.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("pushStart")) {
                    pushStart = field.get(u) == null ? null : Integer.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("pushEnd")) {
                    pushEnd = field.get(u) == null ? null : Integer.valueOf(String.valueOf(field.get(u)));
                } else if (field.getName().equals("timeUnit")) {
                    timeUnit = field.get(u) == null ? null : Integer.valueOf(String.valueOf(field.get(u)));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if (dataSource != null) {
            SdsStandSourceEntity sourceEntity = standSourceService.selectById(dataSource);
            name = itemName + "[" + sourceEntity.getSourceDesc();
        }
        if (dataSourceItem != null) {
            SdsStandSourceFieldEntity sourceFieldEntity = sdsStandSourceFieldService.selectById(dataSourceItem);
            name = name + ":" + sourceFieldEntity.getFieldDesc();
        }
        if (param != null) {
            name = name + " (" + param + ")";
        }

        String timeUnitStr = "";
        //1year、2month、3day、 4hour、5minute、6second
        if (timeUnit == 1) {
            timeUnitStr = "year";
        } else if (timeUnit == 2) {
            timeUnitStr = "month";
        } else if (timeUnit == 3) {
            timeUnitStr = "day";
        } else if (timeUnit == 4) {
            timeUnitStr = "hour";
        } else if (timeUnit == 5) {
            timeUnitStr = "minute";
        } else if (timeUnit == 6) {
            timeUnitStr = "second";
        }
        if (pushStart == null && pushEnd == null) {
            name = name + "]";
        } else {
            if (pushStart != null) {
                name = name + " " + pushStart;
            } else {
                name = name + " ";
            }
            if (pushEnd != null) {
                name = name + "~" + pushEnd + timeUnitStr + "]";
            } else {
                name = name + "~" + " " + timeUnitStr + "]";
            }
        }

        return name;
    }
}
